import requests
from lxml import etree
import json

if __name__ == '__main__':
# UA伪装
    head = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0"
    # 防盗链子
    , "Referer": "https://www.bilibili.com/"
    ,
    "Cookie": "buvid3=A190D14C-631D-DF02-D5A5-096404FBC37B03968infoc; b_nut=1754918203; __at_once=14777538863965270271; buvid4=FF1B3CF8-0E36-86EE-FD0B-DE008B42A4D704832-025081121-uzpRMlKTRTC9owf11MiPyg%3D%3D; buvid_fp=3ade3ed5ec0e8e4f842076c3cd83f03f; SESSDATA=5855bd7c%2C1770470253%2Ce9780%2A82; bili_jct=58dbd5019337564ecbc9021433947565; DedeUserID=496899450; DedeUserID__ckMd5=96c71983351608d5; sid=6xskx0nf; b_lsid=15CC293B_19899481438; _uuid=578A932D-102D3-5931-D86B-F8498A7C34CD94590infoc; CURRENT_QUALITY=0; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTUxNzc1MDAsImlhdCI6MTc1NDkxODI0MCwicGx0IjotMX0.Yv9o--HqipvFX-IOY7JPUOcu1TksECzgbHbpmbEH8Wo; bili_ticket_expires=1755177440; rpdid=|(um~uRuu|J)0J'u~lRmu)J|u; theme-tip-show=SHOWED; CURRENT_FNVAL=4048"
    }

    # 1、指定url
    url = "https://www.bilibili.com/video/BV12z421z75d/?spm_id_from=333.1007.tianma.2-1-4.click&vd_source=4b1ef23e5d47e143cfb702705740719d"

    # 2、发送请求
    response = requests.get(url, headers = head)

    # 3、获取响应的数据
    res_text = response.text

    # 4、数据解析
    tree = etree.HTML(res_text)

    with open("bili2.html", "w", encoding="utf-8") as f:
        f.write(res_text)

        base_info = "".join(tree.xpath("/html/head/script[4]/text()"))[20:]
        print(base_info)
        info_dict = json.loads(base_info)
        print(info_dict)

        video_url = info_dict["data"]["dash"]['video'][0]["baseUrl"]
        audio_url = info_dict["data"]["dash"]['audio'][0]["baseUrl"]

        print(video_url)
        print(audio_url)

        video_content = requests.get(video_url, headers=head).content
        audio_content = requests.get(audio_url, headers=head).content

        # with open("video2.wmv", "wb") as f:
        #     f.write(video_content)
        # with open("audio2.mp4", "wb") as fp:
        #     fp.write(audio_content)